package com.example.administrator.questionanswer;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.questionanswer.adapter.QuestionAdapter;
import com.example.administrator.questionanswer.application.MyApplication;
import com.example.administrator.questionanswer.dao.AnswerBeanDao;
import com.example.administrator.questionanswer.dao.DaoSession;
import com.example.administrator.questionanswer.dao.QuestionBeanDao;
import com.example.administrator.questionanswer.greendao.AnswerBean;
import com.example.administrator.questionanswer.greendao.QuestionBean;
import com.example.administrator.questionanswer.utils.Const;

import org.w3c.dom.Text;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.recycle)
    RecyclerView recyclerView;
    @BindView(R.id.edit_major)
    EditText editText;
    @BindView(R.id.txt_title)
    TextView title;

    QuestionAdapter questionAdapter;
    SharedPreferences sharedPreferences;
    String userName;
    AnswerBeanDao answerBeanDao;

    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        MyApplication.getActivies().add(this);
        title.setActivated(true);
        handler = new Handler();

        sharedPreferences = getSharedPreferences(Const.USER_INFO, MODE_PRIVATE);
        userName = sharedPreferences.getString(Const.USER_NAME, null);
        DaoSession daoSession = MyApplication.getInstances().getDaoSession();
        answerBeanDao = daoSession.getAnswerBeanDao();
        QuestionBeanDao questionBeanDao = daoSession.getQuestionBeanDao();
        List<QuestionBean> questionBeans = questionBeanDao.loadAll();

        questionAdapter = new QuestionAdapter(this);
        questionAdapter.setList(questionBeans);
        recyclerView.setAdapter(questionAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        questionAdapter.notifyDataSetChanged();


    }

    String major;

    @OnClick(R.id.btn_submit)
    public void onclick() {
        List<AnswerBean> answerBeans = answerBeanDao.loadAll();

        if (answerBeans.size() > 0) {
            for (int i = 0; i < answerBeans.size(); i++) {
                AnswerBean answerBean = answerBeans.get(i);
                if (userName.equals(answerBean.getUserName())) {
                    Toast.makeText(this, "您已提交过该问卷，不能再次提交", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

        }


        major = editText.getText().toString();
        if (major == null || "".equals(major)) {
            Toast.makeText(this, "请填写专业", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(Const.USER_MAJOR, major);
        edit.commit();

        showDialog();
    }

    /* 通过监听 触摸事件 动态 隐藏 输入法*/
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /* 获取 点击的 当前的 view 的 范围 */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    AlertDialog alertDialog;

    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        WindowManager windowManager = window.getWindowManager();
        Display defaultDisplay = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.width = (int) (defaultDisplay.getWidth() * 0.8);
        window.setAttributes(attributes);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_register, null);
        alertDialog.setContentView(view);
        window.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_white));
        TextView message = (TextView) view.findViewById(R.id.txt_user_name);
        TextView title = (TextView) view.findViewById(R.id.txt_friends_type);
        TextView txtsure = (TextView) view.findViewById(R.id.txt_accept);
        TextView txtcancle = (TextView) view.findViewById(R.id.txt_refuse);
        message.setText("确认提交？");
        title.setText("提交");
        txtsure.setOnClickListener(onClickListener);
        txtcancle.setOnClickListener(onClickListener);
        alertDialog.setCanceledOnTouchOutside(false);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.txt_accept:
                    alertDialog.dismiss();
                    List<QuestionBean> questionBeans = questionAdapter.getmList();
                    Log.d("MainActivity", "questionBeans:" + questionBeans);

                    for (int i = 0; i < questionBeans.size(); i++) {
                        QuestionBean questionBean = questionBeans.get(i);
                        Long quesrioId = questionBean.getQuesrioId();
                        String questionName = questionBean.getQuestionName();
                        String questionContent = questionBean.getQuestionContent();
                        String questionAContent = questionBean.getQuestionAContent();
                        String questionBContent = questionBean.getQuestionBContent();
                        String questionCContent = questionBean.getQuestionCContent();
                        String questionDContent = questionBean.getQuestionDContent();
                        String questionEContent = questionBean.getQuestionEContent();
                        String questionFContent = questionBean.getQuestionFContent();

                        AnswerBean answerBean = new AnswerBean();
                        answerBean.setQuestionId(quesrioId);
                        answerBean.setQuestionContent(questionContent);
                        answerBean.setUserName(userName);
                        answerBean.setQuestionName(questionName);
                        answerBean.setMajor(major);
                        answerBean.setQuestionAContent(questionAContent);
                        answerBean.setQuestionBContent(questionBContent);
                        answerBean.setQuestionCContent(questionCContent);
                        answerBean.setQuestionDContent(questionDContent);
                        answerBean.setQuestionEContent(questionEContent);
                        answerBean.setQuestionFContent(questionFContent);

                        answerBeanDao.insert(answerBean);
                    }

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "即将进入您的问卷页面", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(MainActivity.this, DataShowActivity.class));
                        }
                    }, 1500);


                    break;
                case R.id.txt_refuse:
                    alertDialog.dismiss();
                    break;
            }
        }
    };

}
